// mircoApp/agency_reward/agency_certificate/agency_certificate.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgPath: app.globalData.imgPath,
    showcarrfootBol: false,
    show:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
    this.getiPnoneBottom();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  getData() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.donation-project.frontend.record.show");
    app._getNetWork({
      url: urlStr,
      data: {
        id: this.options.id
      },
      success: async(response) => {
        let resData = response.data;
        if (resData.result === 1) {
          this.setData({
            info: resData.data.record,
            image_url: resData.data.image_url
          });
          // wx.createSelectorQuery().select('.agency_certificate').fields({
          //   node: true,
          //   size: true,
          // }).exec(async (res) => {
          //   console.log(res[0], 'dddddddddd')
          //   that.setData({
          //     boxW: res[0].width,
          //     boxH: res[0].height
          //   })
          // })
          // wx.getSystemInfo({
          //   success: (res) => {
          //     console.log(res)
          //     that.setData({
          //       boxW: res.windowWidth,
          //       boxH: res.windowHeight,
          //       info: resData.data.record,
          //   image_url: resData.data.image_url
          //     })
          //   }
          // })
          let gbox = await this.getMyCanvasMessage(640,1008);
          that.setData({
            boxW:gbox.width,
            boxH:gbox.height,
            info:resData.data.record,
            image_url:resData.data.image_url
          })
          console.log(await this.getMyCanvasMessage(640,1008),this.data.boxW,this.data.boxH)
        } else {
          wx.showToast({
            title: resData.msg,
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  downImg() {
    if (this.data.isclick) {
      app.tips('海报生成中')
      return
    }
    this.data.isclick = true;
    wx.createSelectorQuery()
      .select('#myCanvas') // 在 WXML 中填入的 id
      .fields({
        node: true,
        size: true
      })
      .exec(async (res) => {
        wx.showLoading({
          title: '加载中',
        })
        // Canvas 对象
        const canvas = res[0].node
        // 渲染上下文
        const ctx = canvas.getContext('2d')

        // Canvas 画布的实际绘制宽高
        const width = res[0].width
        const height = res[0].height

        // 初始化画布大小
        const dpr = wx.getSystemInfoSync().devicePixelRatio;
        canvas.width = width * dpr;
        canvas.height = height * dpr;
        let bg = await this.downImage(this.data.image_url);
        ctx.restore()
        // 画背景
        await this.creatImg(bg, ctx, canvas, canvas.width, canvas.height, 0, 0);
        // ctx.font = `normal ${24*dpr}px Verdana`;
        // ctx.fillStyle = "#000";
        // ctx.textAlign = 'center';
        // ctx.textBaseline = "hanging";
        // ctx.fillText('捐赠证书', canvas.width / 2, 80);
        // ctx.save();
        // ctx.restore();
        // ctx.font = `normal ${15*dpr}px Verdana`;
        // ctx.fillStyle = "#999999";
        // ctx.textAlign = 'center';
        // ctx.textBaseline = "hanging";
        // ctx.fillText(`捐赠证书编号:${this.data.info.certificate_no}`, canvas.width / 2, 180);
        // ctx.save();
        // ctx.restore();
        // ctx.moveTo(24, 300);
        // ctx.lineTo((Number(canvas.width) - 24), 300);
        // ctx.lineHeight = 2;
        // ctx.fillStyle = "#ececec";
        // ctx.stroke();
        // ctx.save();
        // ctx.restore();
        // ctx.font = `normal ${24*dpr}px Verdana`;
        // ctx.fillStyle = "#000";
        // ctx.textAlign = 'center';
        // ctx.textBaseline = "hanging";
        // ctx.fillText(`${this.data.info.member.nickname}`, canvas.width / 2, 550);
        // ctx.font = `normal ${15*dpr}px Verdana`;
        // ctx.fillStyle = "#999999";
        // ctx.textAlign = 'center';
        // ctx.textBaseline = "hanging";
        // ctx.fillText(`捐赠金额`, canvas.width / 2, 750);

        // ctx.font = `normal ${24*dpr}px Verdana`;
        // ctx.fillStyle = "#fe5e56";
        // ctx.textAlign = 'center';
        // ctx.textBaseline = "hanging";
        // ctx.fillText(`￥${this.data.info.amount}`, canvas.width / 2, 870);

        // ctx.font = `normal ${13*dpr}px Verdana`;
        // ctx.fillStyle = "#999999";
        // ctx.textAlign = 'left';
        // ctx.textBaseline = "hanging";
        // ctx.fillText(`订单号:${this.data.info.order.order_sn}`, 24, canvas.height * 0.83);
        // ctx.fillText(`支付时间:${this.data.info.order.order_sn}`, 24, canvas.height * 0.89);
        ctx.save();
        ctx.restore();
        await setTimeout(() => {
          this.toimage(canvas, dpr)
        }, 1000);
      })
  },
  downImage(_url) {
    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url: _url, // 服务器返回的图片地址
        success: (res) => {
          resolve(res.tempFilePath)
        },
        fail: (err) => {
          reject(err)
        }
      })
    })

  },
  creatImg(url, ctx, canvas, w, h, ptop, pleft) {
    return new Promise((resolve, reject) => {
      const image = canvas.createImage();
      let that = this;
      image.src = url
      image.onload = () => {
          // 将图片绘制到 canvas 上
          ctx.drawImage(image, ptop, pleft, w, h)
          resolve(true)
        },
        image.onerror = () => {
          wx.hideLoading();
          that.data.isclick = false;
          resolve(false)
        }
    })
  },
  toimage(canv, dpr) {
    let that = this;
    wx.hideLoading();
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: canv.width * 0.8,
      height: canv.height * 0.8,
      canvas: canv,
      destWidth: this.data.canvasWidth,
      destHeight: this.data.canvasHeight,
      quality: 1,
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        console.log(res)
        that.setData({
          poster: tempFilePath,
          errorFlag: false,
          show: true
        })
        that.data.isclick = false;
      },
      fail: function (res) {
        that.data.isclick = false;
        that.setData({
          errorFlag: true
        })
      }
    });
  },
  getiPnoneBottom() {
    let that = this;
    try {
      var value = wx.getStorageSync("iPhoneBottom");
      if (value) {
        that.setData({
          iPnoneBottomBol: true,
        });
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  previewImage() {
    wx.showToast({
      title: '长按图片分享好友',
      icon: 'none',
      duration: 1800
    })
  },
  async checkWritePotosAlbum() {
    var _this = this;
    let writePhotosAlbum = await this.getAuthSetting('scope.writePhotosAlbum');
    if (!writePhotosAlbum) {
      wx.showModal({
        title: '请开启授权',
        content: '是否跳转设置页开启授权',
        success(res) {
          if (res.confirm) {
            wx.openSetting({
              success(settingdata) {
                if (settingdata.authSetting['scope.writePhotosAlbum']) {
                  _this.saveImg();
                } else {
                  console.log("还是没授权");
                }
              }
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      });
      return;
    }
    this.saveImg();


  },
  saveImg() {

    var imgSrc = this.data.poster;
    wx.downloadFile({
      url: imgSrc,
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: (data) => {
            wx.showToast({
              title: '保存成功',
              icon: 'none',
              duration: 2000
            })
          },
          fail: function (err) {
            console.log(err);
          }
        })
      },
      fail: (err) => {
        wx.saveImageToPhotosAlbum({
          filePath: imgSrc,
          success: (data) => {
            wx.showToast({
              title: '保存成功',
              icon: 'none',
              duration: 2000
            })
          },
          fail: function (err) {
            console.log(err);
          }
        })
        //console.log(err,this.data.poster,"图片下载出错");
      }
    })
  },
  getAuthSetting(authName) {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success(res) {
          if (!res.authSetting[authName]) {
            wx.authorize({
              scope: authName,
              success() {
                resolve(true);
              },
              fail() {
                resolve(false);
              }
            })
          } else resolve(true);
        },
        fail() {
          resolve(false);
        }
      })
    });
  },
  closePopup() {
    this.setData({
      show: false
    })
  },
  // 获取海报画布宽高
  getMyCanvasMessage(w,h) {
    return new Promise((resolve,reject)=>{
      wx.getSystemInfo({
        success: (res) => {
          let scale = h/w;
          let width = res.screenWidth - (res.screenWidth*0.2);
          let height = width*scale;
          resolve({
            //width,height,contentScale
            width:width,height:height
          });

        },
        fail:(res)=>{
          this.data.getFlag=true;
        }
      })
    })

  },
})